package com.xiaoyun.alllearning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoyun.alllearning.domain.common.PageQuery;
import com.xiaoyun.alllearning.domain.common.PageResult;
import com.xiaoyun.alllearning.domain.dto.UserDTO;
import com.xiaoyun.alllearning.domain.dto.UserQueryDTO;
import com.xiaoyun.alllearning.domain.entity.UserDO;
import com.xiaoyun.alllearning.mapper.UserMapper;
import com.xiaoyun.alllearning.service.UserService;
import com.xiaoyun.alllearning.util.ValidatorUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {


    @Override
    public int save(UserDTO userDTO) {
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(userDTO, userDO);
        return this.baseMapper.insert(userDO);
    }

    @Override
    public int update(Long id, UserDTO userDTO) {
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(userDTO, userDO);
        userDO.setId(id);
        return this.baseMapper.updateById(userDO);
    }

    @Override
    public int delete(Long id) {
        return this.baseMapper.deleteById(id);
    }

    @Override
    public PageResult<List<UserDTO>> query(PageQuery<UserQueryDTO> pageQuery) {
        //手动校验
        ValidatorUtils.validate(pageQuery);

        Page page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
        UserDO query = new UserDO();
        BeanUtils.copyProperties(pageQuery.getQuery(), query);

        IPage<UserDO> userDOIPage = this.baseMapper.selectPage(page, new QueryWrapper<>(query));

        PageResult<List<UserDTO>> pageResult = new PageResult<>();
        pageResult.setPageNo((int) userDOIPage.getCurrent());
        pageResult.setPageSize((int) userDOIPage.getSize());
        pageResult.setTotal(userDOIPage.getTotal());
        pageResult.setPageNum(userDOIPage.getPages());

        List<UserDTO> userDTOList = Optional.ofNullable(userDOIPage.getRecords())
                .map(List::stream)
                .orElseGet(Stream::empty)
                .map(userDO -> {
                    UserDTO userDTO = new UserDTO();
                    BeanUtils.copyProperties(userDO, userDTO);
                    return userDTO;
                }).collect(Collectors.toList());
        pageResult.setData(userDTOList);
        return pageResult;
    }
}
